import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Input, Select, Button, Pagination, Alert, Rate, Space, Card, Typography } from 'antd';
import { SearchOutlined, ArrowLeftOutlined, StarOutlined, StarFilled } from '@ant-design/icons';
import KeyStrategyDisplay from './KeyStrategyDisplay'; 
import './index.scss';

const { Option } = Select;
const { Title, Text } = Typography;

const mockBooks = [
  { id: '1', title: 'Vue.js高级编程', author: '张三', category: '编程', rating: 4.5, price: '￥68.00', sales: 1200, coverUrl: 'https://via.placeholder.com/150x200?text=VueBook' },
  { id: '2', title: 'React Hooks实战', author: '李四', category: '编程', rating: 4.8, price: '￥75.00', sales: 1500, coverUrl: 'https://via.placeholder.com/150x200?text=ReactBook' },
  { id: '3', title: 'CSS揭秘', author: '王五', category: '设计', rating: 4.2, price: '￥55.00', sales: 800, coverUrl: 'https://via.placeholder.com/150x200?text=CSSBook' },
  { id: '4', title: '算法导论', author: '赵六', category: '计算机科学', rating: 4.9, price: '￥120.00', sales: 2000, coverUrl: 'https://via.placeholder.com/150x200?text=AlgorithmBook' },
  { id: '5', title: '数据结构与算法', author: '钱七', category: '计算机科学', rating: 4.7, price: '￥99.00', sales: 1800, coverUrl: 'https://via.placeholder.com/150x200?text=DSABook' },
  { id: '6', title: '设计模式', author: '孙八', category: '设计', rating: 4.3, price: '￥60.00', sales: 950, coverUrl: 'https://via.placeholder.com/150x200?text=DesignPattern' },
  { id: '7', title: 'JavaScript高级程序设计', author: '周九', category: '编程', rating: 4.6, price: '￥88.00', sales: 1600, coverUrl: 'https://via.placeholder.com/150x200?text=JSBook' },
  { id: '8', title: 'Python机器学习', author: '吴十', category: '人工智能', rating: 4.7, price: '￥110.00', sales: 1300, coverUrl: 'https://via.placeholder.com/150x200?text=PythonML' },
  { id: '9', title: '深入浅出Node.js', author: '郑十一', category: '编程', rating: 4.4, price: '￥72.00', sales: 1100, coverUrl: 'https://via.placeholder.com/150x200?text=NodeBook' },
  { id: '10', title: '人工智能伦理', author: '魏十二', category: '人工智能', rating: 4.0, price: '￥45.00', sales: 600, coverUrl: 'https://via.placeholder.com/150x200?text=AIEthics' },
  { id: '11', title: '网络安全基础', author: '冯十三', category: '计算机科学', rating: 4.1, price: '￥58.00', sales: 750, coverUrl: 'https://via.placeholder.com/150x200?text=SecurityBook' },
  { id: '12', title: '云计算概论', author: '陈十四', category: '计算机科学', rating: 4.0, price: '￥65.00', sales: 900, coverUrl: 'https://via.placeholder.com/150x200?text=CloudBook' },
  { id: '13', title: '设计心理学', author: '褚十五', category: '设计', rating: 4.6, price: '￥70.00', sales: 1000, coverUrl: 'https://via.placeholder.com/150x200?text=DesignPsych' },
  { id: '14', title: '数据可视化', author: '卫十六', category: '数据科学', rating: 4.5, price: '￥80.00', sales: 1150, coverUrl: 'https://via.placeholder.com/150x200?text=DataViz' },
  { id: '15', title: '编译原理', author: '蒋十七', category: '计算机科学', rating: 4.7, price: '￥130.00', sales: 1400, coverUrl: 'https://via.placeholder.com/150x200?text=CompilerBook' },
  { id: '16', title: '移动应用开发', author: '沈十八', category: '编程', rating: 4.3, price: '￥90.00', sales: 980, coverUrl: 'https://via.placeholder.com/150x200?text=MobileDev' },
];


const mockStore = {
  _state: {
    books: [],
    keyStrategy: 'id', 
  },
  dispatch(action) {
    if (action === 'fetchBooks') {
      return new Promise(resolve => {
        setTimeout(() => {
          this._state.books = mockBooks;
          resolve();
        }, 500); 
      });
    }
  },
  getState() {
    return this._state;
  },
  subscribe(listener) {
    
    
    return () => {}; 
  }
};

const useNavigate = () => {
  return (path) => {
    console.log(`Navigating to: ${path}`);
    
  };
};

const AllBooks = () => {
  const navigate = useNavigate();

  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [sortBy, setSortBy] = useState('rating');
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [books, setBooks] = useState([]);

  
  useEffect(() => {
    const handleStateChange = () => {
      setBooks(mockStore.getState().books);
    };
    
    handleStateChange();
    const unsubscribe = mockStore.subscribe(handleStateChange);
    return () => unsubscribe();
  }, []);

  
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category');
    if (category) {
      setCategoryFilter(category);
    }
  }, []);

  
  useEffect(() => {
    const fetchInitialBooks = async () => {
      setLoading(true);
      setError(null);
      try {
        if (!books || books.length === 0) {
          await mockStore.dispatch('fetchBooks');
        }
      } catch (err) {
        setError('加载图书数据失败，请稍后重试');
        console.error('Error loading books:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchInitialBooks();
  }, [books]); 

  const categories = useMemo(() => {
    return [...new Set(books.map(book => book.category))];
  }, [books]);

  const filteredBooks = useMemo(() => {
    let result = [...books];

    
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(book =>
        book.title.toLowerCase().includes(query) ||
        book.author.toLowerCase().includes(query)
      );
    }

    
    if (categoryFilter) {
      result = result.filter(book => book.category === categoryFilter);
    }

    
    result.sort((a, b) => {
      switch (sortBy) {
        case 'rating':
          return b.rating - a.rating;
        case 'sales':
          return b.sales - a.sales;
        case 'priceAsc':
          return parseFloat(a.price.replace('￥', '')) - parseFloat(b.price.replace('￥', ''));
        case 'priceDesc':
          return parseFloat(b.price.replace('￥', '')) - parseFloat(a.price.replace('￥', ''));
        default:
          return 0;
      }
    });

    
    const start = (currentPage - 1) * 12; 
    const end = start + 12;
    return result.slice(start, end);
  }, [books, searchQuery, categoryFilter, sortBy, currentPage]);

  const totalBooks = useMemo(() => books.length, [books]);
  const totalPages = useMemo(() => Math.ceil(totalBooks / 12), [totalBooks]); 

  const goBack = useCallback(() => {
    navigate('/');
  }, [navigate]);

  const viewBookDetail = useCallback((bookId) => {
    navigate(`/book/${bookId}`);
  }, [navigate]);

  const handlePageChange = useCallback((page) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  
  
  const getItemKey = useCallback((book, index) => {
    
    const keyStrategy = mockStore.getState().keyStrategy; 

    switch (keyStrategy) {
      case 'id':
        return book.id;
      case 'index':
        return index;
      case 'key': 
        return book.key || book.id || index;
      case 'none': 
      default:
        return book.id || index;
    }
  }, []);

  return (
    <div className="all-books">
      <div className="page-header">
        <Title level={1}>全部图书</Title>
        <Space>
          <KeyStrategyDisplay />
          <Button icon={<ArrowLeftOutlined />} onClick={goBack}>
            返回
          </Button>
        </Space>
      </div>

      <div className="filter-section">
        <Input
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="搜索图书..."
          prefix={<SearchOutlined />}
          allowClear
          className="search-input"
        />
        <Select
          value={categoryFilter}
          onChange={setCategoryFilter}
          placeholder="选择分类"
          allowClear
          style={{ width: 180 }}
        >
          {categories.map(category => (
            <Option key={category} value={category}>{category}</Option>
          ))}
        </Select>
        <Select
          value={sortBy}
          onChange={setSortBy}
          placeholder="排序方式"
          style={{ width: 180 }}
        >
          <Option value="rating">评分最高</Option>
          <Option value="sales">销量最高</Option>
          <Option value="priceAsc">价格从低到高</Option>
          <Option value="priceDesc">价格从高到低</Option>
        </Select>
      </div>

      {loading ? (
        <div className="loading-state">
          <Alert
            message="加载中..."
            type="info"
            showIcon
          />
        </div>
      ) : error ? (
        <div className="error-state">
          <Alert
            message="加载失败"
            description={error}
            type="error"
            showIcon
          />
        </div>
      ) : (
        <>
          <div className="books-grid">
            {filteredBooks.map((book, index) => (
              <Card
                key={getItemKey(book, index)}
                className="book-card"
                hoverable
                onClick={() => viewBookDetail(book.id)}
              >
                <div className="book-cover">
                  <img src={book.coverUrl} alt={book.title} />
                  <div className="book-hover">
                    <Button type="primary" shape="round" size="small">
                      查看详情
                    </Button>
                  </div>
                </div>
                <Card.Meta
                  className="book-info"
                  title={
                    <Title level={3} className="book-title-text" ellipsis={{ rows: 2 }}>
                      {book.title}
                    </Title>
                  }
                  description={
                    <>
                      <div className="book-meta">
                        <Text className="book-author">{book.author}</Text>
                        <Tag className="book-category">{book.category}</Tag>
                      </div>
                      <div className="book-rating">
                        <Rate
                          disabled
                          allowHalf
                          defaultValue={book.rating}
                          character={({ index }) => <StarFilled />}
                          className="stars"
                        />
                        <Text className="rating-value">{book.rating}</Text>
                      </div>
                      <div className="book-footer">
                        <Text strong className="book-price">{book.price}</Text>
                        <Text className="book-sales">销量 {book.sales}</Text>
                      </div>
                    </>
                  }
                />
              </Card>
            ))}
          </div>

          {totalPages > 1 && (
            <div className="pagination-section">
              <Pagination
                background
                current={currentPage}
                total={totalBooks}
                pageSize={12}
                onChange={handlePageChange}
                showLessItems 
              />
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default AllBooks;